import { app, shell, BrowserWindow, BrowserView, ipcMain } from 'electron'
import { screen } from 'electron/main'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

// import { Plugin } from './@types'
import path from 'path'

function createWindow(): BrowserWindow {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 900,
    height: 660,
    show: false,
    autoHideMenuBar: true,
    frame: false,
    titleBarStyle: 'hidden',
    trafficLightPosition: { x: 12, y: 20 },
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      contextIsolation: true
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  // 拦截主窗口中的超链接点击事件，openExternal是调用系统能力打开。比如打开一个文档，就会用系统默认的编辑器打开
  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(`${process.env['ELECTRON_RENDERER_URL']}/mainWindow`)
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  return mainWindow
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  const win = createWindow()

  createView(win)

  ipcMain.on('msg-trigger', (_, args) => {
    if (args.type === 'windowMoving') {
      const { mouseX, mouseY, width, height } = args.data
      const { x, y } = screen.getCursorScreenPoint()
      // 获取当前需要移动的窗口
      if (!win) return
      // 重新设置窗口位置
      win.setBounds({ x: x - mouseX, y: y - mouseY, width, height })
    }
  })

  app.on('activate', function () {
    // On macOS, it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// 处理非 macOS 下的所有窗口关闭后的逻辑：退出整个 electron 应用
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

function createView(win: BrowserWindow) {
  // const { preloadPath } = plugin

  const view = new BrowserView({
    webPreferences: {
      // preload: preloadPath,
      nodeIntegration: false,
      contextIsolation: true
    }
  })

  win.setBrowserView(view)
  view.setBounds({ x: 0, y: 60, width: 900, height: 600 })

  console.log(path.join('plugins', './index.html'))
  view.webContents.loadFile(`${path.join('plugins', './index.html')}`)
  // view.webContents.loadURL(`${process.env['ELECTRON_RENDERER_URL']}/plugins/todo`)

  // view.webContents.on('dom-ready', () => {
  //   view.webContents.loadURL('https://juejin.cn')
  // })
}
